package com.apestech.api.exp;

import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.ImportedKey;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.LocalVariable;
import com.apestech.framework.util.StringUtil;
import com.apestech.framework.xml.pub.WriteXml;
import org.dom4j.Element;
import java.io.File;
import java.util.ArrayList;

public class ExpExp extends StringUtil{
    private SqlSession ssession;
    private SqlSession dsession;
    private String stabname;
    private String dtabname;
    private String zdtabname;
    private Table stable;
    private Table dtable;
    private ArrayList<String> rkeylist;
    private WriteXml xml;
    private Element root;
    private Element top;
    private JSONObject sRemark;
    private JSONObject ctable;
    private JSONObject expmap;

    public ExpExp(SqlSession ssession, SqlSession dsession, String stabname, String dtabname) throws Exception {
        this.ssession=ssession;
        this.dsession=dsession;
        this.stabname=stabname;
        this.dtabname=dtabname;
        stable=ssession.getDictTable(stabname);
        dtable=dsession.getDictTable(dtabname);
        rkeylist=new ArrayList<String>();
        sRemark=LocalVariable.getSysDbTableRemark(ssession);
        ctable=new JSONObject();
    }

    public JSONObject getCtable() {
        return ctable;
    }

    public void setCtable(JSONObject ctable) {
        this.ctable = ctable;
    }

    public void setXml(WriteXml xml) {
        this.xml = xml;
    }

    public void setRoot(Element root) {
        this.root = root;
    }

    public String getZdtabname() {
        return zdtabname;
    }

    public void setZdtabname(String zdtabname) {
        this.zdtabname = zdtabname;
    }

    public void createInputXml() throws Exception {
        if(xml==null){
            xml=new WriteXml();
            root=xml.createXml();
        }
        expmap=ExpUtil.getMapping();
        JSONObject sysm=ExpUtil.getSysMap();
        String noTab=((JSONObject)expmap.get("noTab")).getString("table");
        top=root.addElement("expTable");
        top.addAttribute("id", dtabname);
        top.addAttribute("source", stabname);
        addParty();
        iniFk(dtable, dtabname);
        if(rkeylist.contains(dtabname)) rkeylist.remove(dtabname);
        int len=rkeylist.size();
        if(len>0){
            Element fk=null;
            if(zdtabname==null){
                fk=top.addElement("fkkey");
            }
            //Element SysMap=fk.addElement("SysMap");
            for(int i=0; i<len; i++){
                String st=rkeylist.get(i);
                if((","+noTab+",").indexOf(","+st+",")>=0){
                    continue;
                }
                Element ftab=null;
                if(zdtabname==null){
                    ftab=fk.addElement("fkTable");
                    ftab.addAttribute("id", st);
                }

                String sremark=dsession.getTableRemark(st);
                String dt=null;
                if(sRemark.get(sremark)!=null){
                    dt=sRemark.getString(sremark);
                }

                if(dt==null){
                    dt=sysm.getString(st);
                    if(dt==null || "".equals(dt.trim())) dt=null;
                }
                if(dt!=null) {
                    //SysMap.addAttribute(st,dt);
                    if(ctable.get(st)==null){
                        ExpExp ext=new ExpExp(ssession, dsession, dt, st);
                        ctable.put(st, "1");
                        ext.setCtable(ctable);
                        ext.setXml(xml);
                        ext.setRoot(root);
                        if(zdtabname==null) ext.setZdtabname(dtabname);
                        else ext.setZdtabname(zdtabname);
                        ext.createInputXml();
                    }
                }
            }
        }
        iniField();
    }

    public void writeXml() throws Exception {
        String sep=File.separator;
        String xmlFileName=LocalVariable.getRootDir()+ sep+"temp"+sep+"script"+sep+this.dtabname+".xml";
        xml.writeXml(xmlFileName);
    }

    private void addParty() throws Exception {
        rkeylist.add("SOE_SCENE");
        rkeylist.add("MAS_ACCESS_PROVIDER");
        rkeylist.add("SOE_BUSINESS_TYPE");
        rkeylist.add("SOE_BUSINESS_ATTR");
        rkeylist.add("SOE_BUSINESS_ATTR_VALUE");
        rkeylist.add("MAS_PARTY");
        rkeylist.add("MAS_ROLE");
        rkeylist.add("MAS_PARTY_ROLE");
    }

    private ArrayList<String> getFkTable(String[] tabs){
        int len=tabs.length;
        ArrayList<String> list=new ArrayList<String>();
        for(int i=0; i<len; i++){
            if(!rkeylist.contains(tabs[i]));
            list.add(tabs[i]);
        }
        return list;
    }

    private void iniFk(Table table, String tabname) throws Exception {
        if(table==null) return;
        ImportedKey impkey=table.getPkFKey();
        if(!rkeylist.contains(tabname)) {
            rkeylist.add(tabname);
        }
        if(impkey==null) return;
        ArrayList<String> tabs=getFkTable(impkey.getPkTableList());
        int len=tabs.size();
        for(int i=0; i<len; i++){
            String stab=tabs.get(i);
            if(!rkeylist.contains(stab)){
                iniFk(dsession.getDictTable(stab), stab);
            }
            if(i==len-1){
                if(!rkeylist.contains(stab))
                    rkeylist.add(stab);
            }
        }
    }

    private void iniField() throws Exception {
        //Element fields=top.addElement("mapping");
        Element fields=top;
        //Element SysMap=fields.addElement("SysMap");
        Element NoMap=fields.addElement("NoMap");
        JSONObject sysm=ExpUtil.getTabSysMap(dtabname);
        String[] cols=dtable.getColumn().split(",");
        String col="";
        int len=cols.length;
        for(int i=0; i<len; i++){
            String field=cols[i];
            if(!"".equals(field)){
                String remark=dtable.getRemarks(field);
                String sfield=stable.getFieldByRemark(remark);
                if(sfield==null && sysm!=null){
                    sfield=sysm.getString(field);
                }
                if(sfield!=null){
                    if(!"".equals(col)) col=col+",";
                    if(stable.isField(sfield)){
                        col=col+"A."+sfield+" AS "+field;
                    } else col=col+"'"+sfield+"' AS "+field;
                    //SysMap.addAttribute(field, sfield);
                    //fields.addAttribute(field, sfield);
                } else {
                    NoMap.addAttribute(field, remark);
                    //fields.addAttribute(field, remark);
                }
            }
        }
        if(!col.equals("")){
            Element esql=top.addElement("sql");
            esql.addCDATA("SELECT "+col+" FROM "+stabname+" A WHERE 1=1 ");
        }
    }

}
